# cython: language_level=3
from typing import Dict, Optional
import numpy as np

from sanic.response import HTTPResponse

from utils.common import SampleJsonEncoder, json

"""
Author: Gaoqiang Du
Description：通用的业务响应方法
Date: 2022/2/5 12:56
"""

class NumpyJsonEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.integer):
            return int(obj)  # 将 int64 类型转换为 Python 内置的整数类型
        return super().default(obj)

def general_json_res(
        status: int = 200,
        msg: str = "success",
        http_status: int = 200,
        headers: Optional[Dict[str, str]] = None,
        **kwargs
) -> HTTPResponse:
    # According to business requirements, rewrite response
    data = {'status': status, 'msg': msg}
    if kwargs:
        data["data"], kwargs = kwargs, {}

    # 转换 int64 类型为整数类型
    data = convert_int64_to_int(data)

    return HTTPResponse(
        json.dumps(data, cls=SampleJsonEncoder, ensure_ascii=False, **kwargs),
        # json.dumps(data, ensure_ascii=False, **kwargs),
        headers=headers,
        status=http_status,
        content_type="application/json",
    )
    
def convert_int64_to_int(data):
    for key, value in data.items():
        if isinstance(value, dict):
            data[key] = convert_int64_to_int(value)
        elif isinstance(value, np.integer):
            data[key] = int(value)
    return data
